package org.jeecg.modules.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.expr.instruct.ForEach;
import org.jeecg.common.api.diy.ProfessorApi;
import org.jeecg.common.system.api.ISysBaseAPI;

import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.entity.DiyProfessiorPoint;
import org.jeecg.modules.entity.DiyProfessorInfo;
import org.jeecg.modules.entity.DiyProfessorScore;
import org.jeecg.modules.mapper.DiyProfessorInfoMapper;
import org.jeecg.modules.service.DiyProfessiorPointService;
import org.jeecg.modules.service.DiyProfessorScoreService;
import org.jeecg.modules.service.IDiyProfessorInfoService;
import org.jeecg.modules.temporary.entity.DiyTemporaryApplicantInfo;
import org.jeecg.modules.temporary.mapper.DiyTemporaryApplicantInfoMapper;
import org.jeecg.modules.temporary.service.IDiyTemporaryApplicantInfoService;
import org.jeecg.modules.util.ConstantDiy;
import org.jeecg.modules.util.SplitUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 专家信息录入
 * @Author: jeecg-boot
 * @Date: 2020-05-21
 * @Version: V1.0
 */

@Service
@Slf4j
public class DiyProfessorInfoServiceImpl extends ServiceImpl<DiyProfessorInfoMapper, DiyProfessorInfo> implements IDiyProfessorInfoService {
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
    @Autowired
    private DiyProfessorInfoMapper diyProfessorInfoMapper;
    @Autowired
    private IDiyTemporaryApplicantInfoService diyTemporaryApplicantInfoService;
    @Autowired
    private DiyProfessorScoreService diyProfessorScoreService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private DiyProfessiorPointService diyProfessiorPointService;
    @Autowired
    private IDiyTemporaryApplicantInfoService iDiyTemporaryApplicantInfoService;
    @Autowired
    private ProfessorApi professorApi;

    @Override
    public String getDeclareCategoryName(String id) {
        String name = diyProfessorInfoMapper.selDictNameById(id);
        return name;
    }

    @Override
    public String getDingDinguserid(String id) {
        return diyProfessorInfoMapper.getDingDinguserid(id);
    }

    @Override
    public String selPhone(String id) {
        return diyProfessorInfoMapper.selPhone(id);
    }

    @Override
    public String getDeclareCategoryIdByName(String name) {
        return diyProfessorInfoMapper.selDictIdByName(name);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveByJsonObj(JSONObject obj, String dingUserId) {
        // 获得审批实例
        String process_instance = obj.getString("process_instance");
        // 获得表单组件
        JSONObject object = JSON.parseObject(process_instance);
        String form_component_values = object.getString("form_component_values");

        // 获得数组
        JSONArray objects = JSON.parseArray(form_component_values);
        JSONObject jsonObject = null;


        // 初始化专家信息对象

        DiyProfessorInfo diyProfessorInfo = new DiyProfessorInfo();
        log.info("dingUserId"+dingUserId);
        try {
            diyProfessorInfo=noauth2(dingUserId);
            log.info("方法noauth2返回回来的专家信息"+diyProfessorInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //遍历
//        for (int i = 0; i < objects.size(); i++) {
//            jsonObject = objects.getJSONObject(i);
//            String name = jsonObject.getString("name");
//            String value = jsonObject.getString("value");
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//
//                switch (name) {
//                    case ConstantDiy.D_NAME:
//                        diyProfessorInfo = noauth2(value);
//   /*                     diyProfessorInfo.setProfessorName(value);
//                        diyProfessorScore.setProfessorName(value);
//                        break;
//                    case ConstantDiy.D_SEX:
//                        diyProfessorInfo.setProfessorSex("男".equals(value) ? 1 : 2);
//                        break;
//                    case ConstantDiy.D_ADDRESS:
//                        diyProfessorInfo.setProfessorAddress(value);
//                        break;
//                    case ConstantDiy.D_BIRTHDAY:
//                        Date date = sdf.parse(value);
//                        diyProfessorInfo.setProfessorBirthday(date);
//                        break;
//                    case ConstantDiy.D_SCHOOL:
//                        diyProfessorInfo.setProfessorSchool(value);
//                        break;
//                    case ConstantDiy.D_PHONE:
//                        diyProfessorInfo.setProfessorPhone(value);
//                        break;
//                    case ConstantDiy.D_PROJECT:
//                        diyProfessorInfo.setProfessorProjectIntroduce(value);
//                        break;
//                    case ConstantDiy.D_PHOTO:
//                        // 去掉前边的路径
//                        String[] split = value.split(ConstantDiy.IMG_URL_FONT);
//                        // 去掉"和之后的东西
//                        String[] split1 = split[1].split("\"");
//                        diyProfessorInfo.setProfessorPhoto(split1[0].getBytes());
//                        diyProfessorInfo.setProfessorPhotoString(split1[0]);
//                        break;
//                    case ConstantDiy.D_INFOPHOTO:
//                        // 去掉前边的路径
//                        String[] split4 = value.split(ConstantDiy.IMG_URL_FONT);
//                        // 去掉"和之后的东西
//                        String[] split5 = split4[1].split("\"");
//                        diyProfessorInfo.setProfessorInfoPhoto(split5[0].getBytes());
//                        diyProfessorInfo.setProfessorInfoPhotoString(split5[0]);
//                        break;
//                    case ConstantDiy.D_MAJOR:
//                        // 把专业转换成id
//                        String majorId = professorApi.queryMajorIdByName(value);
//                        diyProfessorInfo.setProfessorMajor(majorId);
//                        break;
//                    case ConstantDiy.D_MAJORDATE:
//                        diyProfessorInfo.setProfessorMajorDate(sdf.parse(value));
//                        break;
//                    case ConstantDiy.D_GRADUATE:
//                        diyProfessorInfo.setProfessorGraduateDate(sdf.parse(value));
//                        break;
//                    case ConstantDiy.D_EDUCATIONBACKGROUND:
//                        diyProfessorInfo.setProfessorEducationBackground(value);
//                        break;
//                    case ConstantDiy.D_DEGREE:
//                        diyProfessorInfo.setProfessorDegree(value);
//                        break;
//                    case ConstantDiy.D_WORKUNIT:
//                        diyProfessorInfo.setProfessorWorkUnit(value);
//                        break;
//                    case ConstantDiy.D_DECLARECATEGORY:
//                        //"申报类别"
//                        // 根据,截取name
//                        diyProfessorScore.setProfessorDeclareCategoryName(value);
//                        // 把钉钉回调的专家申报类别变成id传入数据库中
//                            DiyTemporaryApplicantInfo id = iDiyTemporaryApplicantInfoService.getOne(new QueryWrapper<DiyTemporaryApplicantInfo>().eq("ding_user_id", dingUserId));
//                            diyProfessorInfo.setProfessorDeclareCategory(id.getProfessorDeclareCategory());
//                            diyProfessorScore.setProfessorDeclareCategory(id.getProfessorDeclareCategory());
//                        break;
//                    case ConstantDiy.D_POSITION:
//                        diyProfessorInfo.setProfessorPosition(value);
//                        break;
//                    case ConstantDiy.D_BEGINWORK:
//                        diyProfessorInfo.setProfessorBeginWork(sdf.parse(value));
//                        break;
//                    case ConstantDiy.D_TITLE:
//                        diyProfessorInfo.setProfessorTitle(value);
//                        diyProfessorScore.setProfessorTitle(value);
//                        List<DiyProfessiorPoint> list = diyProfessiorPointService.list(new QueryWrapper<DiyProfessiorPoint>().eq("id", "2"));
//                        List<DiyProfessiorPoint> list2 = diyProfessiorPointService.list(new QueryWrapper<DiyProfessiorPoint>().eq("id", "1"));
//                        String str = "";
//                        if(list.get(0).getPointA().equals(value))
//                        {
//                            str=list2.get(0).getPointA();
//                        }
//                        if(list.get(0).getPointB().equals(value))
//                        {
//                            str=list2.get(0).getPointB();
//                        }
//                        if(list.get(0).getPointC().equals(value))
//                        {
//                            str=list2.get(0).getPointC();
//                        }
//                        if(list.get(0).getPointD().equals(value))
//                        {
//                            str=list2.get(0).getPointD();
//                        }
//                        if(list.get(0).getPointE().equals(value))
//                        {
//                            str=list2.get(0).getPointE();
//                        }
//                        if(list.get(0).getPointF().equals(value))
//                        {
//                            str=list2.get(0).getPointF();
//                        }
//                        diyProfessorScore.setTechnicalTitleScore(Integer.parseInt(str));
//                        break;
//                    case ConstantDiy.D_WORKMAJOR:
//                        diyProfessorInfo.setProfessorWorkMajor(value);
//                        break;
//                    case ConstantDiy.D_IDENTITY:
//                        diyProfessorInfo.setProfessorIdentity(value);
//                        break;
//                    case ConstantDiy.D_HOMEADDRESS:
//                        diyProfessorInfo.setProfessorHomeAddress(value);
//                        break;
//                    case ConstantDiy.D_HEALTH:
//                        diyProfessorInfo.setProfessorHealth(value);
//                        break;
//                    case ConstantDiy.D_OFFICE:
//                        diyProfessorInfo.setProfessorOfficeTel(value);
//                        break;
//                    case ConstantDiy.D_LEADMSG:
//                        diyProfessorInfo.setProfessorLeadMsg("");
//                        break;
//                        //身份证复印件一张
//                    case ConstantDiy.D_ID:
//                        String[] split01 = value.split(ConstantDiy.IMG_URL_FONT);
//                        String[] split02 = split01[1].split("\"");
//                        diyProfessorInfo.setProfessorId(split02[0].getBytes());
//                        diyProfessorInfo.setProfessorIdString(split02[0]);
//                        break;
//                        //个人承若书一张
//                    case ConstantDiy.D_COMMITMENT:
//                        String[] split03 = value.split(ConstantDiy.IMG_URL_FONT);
//                        String[] split04 = split03[1].split("\"");
//                        diyProfessorInfo.setProfessorCommitment(split04[0].getBytes());
//                        diyProfessorInfo.setProfessorCommitmentString(split04[0]);
//                        break;
//                        //专业资格职业证书复印件
//                    case ConstantDiy.D_QUALIFICATION:
//                        String string01= SplitUtil.splitutil(value);
//                        diyProfessorInfo.setProfessorQualification(string01.getBytes());
//                        diyProfessorInfo.setProfessorQualificationString(string01);
//                        break;
//                        //个人工作简历
//                    case ConstantDiy.D_RESUME:
//                        String string02= SplitUtil.splitutil(value);
//                        diyProfessorInfo.setProfessorResume(string02.getBytes());
//                        diyProfessorInfo.setProfessorResumeString(string02);
//                        break;
//                        //学历、学位证书复印件
//                    case ConstantDiy.D_DEGREEIMAGE:
//                        String string03= SplitUtil.splitutil(value);
//                        diyProfessorInfo.setProfessorDegreeImage(string03.getBytes());
//                        diyProfessorInfo.setProfessorDegreeImageString(string03);
//                        break;
//                        //其他证明专业能力的材料
//                    case ConstantDiy.D_OTHER:
//                        String string04= SplitUtil.splitutil(value);
//                        diyProfessorInfo.setProfessorOther(string04.getBytes());
//                        diyProfessorInfo.setProfessorOtherString(string04);
//                        break;
////                    case ConstantDiy.D_APPROVEMSG:
////                        diyProfessorInfo.setProfessorApproveMsg(value);
////                        break;*/
//                    break;
//                    default:
//                        break;
//                }
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

        // 获得行政审批意见
        String operation_records = object.getString("operation_records");
        // 获得数组
        JSONArray operation_records_array = JSON.parseArray(operation_records);
        // 遍历数组
        for (int i = 0; i < operation_records_array.size(); i++) {
            // 获取审批意见
            String remark = operation_records_array.getJSONObject(i).getString("remark");
            if (remark != null && !"".equals(remark.trim())) {
                // 把审批意见放入对象中
                diyProfessorInfo.setProfessorApproveMsg(remark);
            }
        }
        diyProfessorInfo.setDelFlag(0);
        log.info("正在处理专家的信息为"+diyProfessorInfo);
        DiyProfessorInfo info = diyProfessorInfoMapper.selectInfoByDIngUserId(dingUserId);
        if (info != null) {
            // 执行更新操作
            //diyProfessorInfoMapper.deleteDingDinguserid(dingUserId);
            //diyProfessorInfoMapper.insert(diyProfessorInfo);
            // 先修改专家状态为在岗
            diyProfessorInfoMapper.updateDiyProfessorDelFlag(0,dingUserId);
            // 更新用户信息
            QueryWrapper<DiyProfessorInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("ding_user_id",dingUserId);
            diyProfessorInfoMapper.update(diyProfessorInfo,wrapper);
            log.info("专家修改个人信息成功 ==> {} ", diyProfessorInfo);
        } else {
            diyProfessorInfoMapper.insert(diyProfessorInfo);
            log.info("审批专家通过，保存数据库中 ==> {} ", diyProfessorInfo);
        }
    }
    public DiyProfessorInfo noauth2(String name) throws Exception {
        DiyTemporaryApplicantInfo one = diyTemporaryApplicantInfoService.getOne(new QueryWrapper<DiyTemporaryApplicantInfo>().eq("ding_user_id", name));
        log.info("one"+one);//现在的问题是到这部了 然后下去的时候返回的是空
        DiyProfessorInfo diyProfessorInfo = new DiyProfessorInfo();
        DiyProfessorScore diyProfessorScore = new DiyProfessorScore();
        BeanUtils.copyProperties(one,diyProfessorInfo );
        log.info("copyPropertiesDiyProfessorInfo====================》"+diyProfessorInfo);
        BeanUtils.copyProperties(one,diyProfessorScore);
        log.info("copyPropertiesDiyProfessorScore====================》"+diyProfessorScore);
        diyProfessorInfo.setIsLeave(0);
        List<DiyProfessiorPoint> list = diyProfessiorPointService.list(new QueryWrapper<DiyProfessiorPoint>().eq("id", "2"));
        List<DiyProfessiorPoint> list2 = diyProfessiorPointService.list(new QueryWrapper<DiyProfessiorPoint>().eq("id", "1"));
        String str = "";
        if(list.get(0).getPointA().equals(diyProfessorScore.getProfessorTitle()))
        {
            str=list2.get(0).getPointA();
        }
        if(list.get(0).getPointB().equals(diyProfessorScore.getProfessorTitle()))
        {
            str=list2.get(0).getPointB();
        }
        if(list.get(0).getPointC().equals(diyProfessorScore.getProfessorTitle()))
        {
            str=list2.get(0).getPointC();
        }
        if(list.get(0).getPointD().equals(diyProfessorScore.getProfessorTitle()))
        {
            str=list2.get(0).getPointD();
        }
        if(list.get(0).getPointE().equals(diyProfessorScore.getProfessorTitle()))
        {
            str=list2.get(0).getPointE();
        }
        if(list.get(0).getPointF().equals(diyProfessorScore.getProfessorTitle()))
        {
            str=list2.get(0).getPointF();
        }
        diyProfessorScore.setTechnicalTitleScore(Integer.parseInt(str));
        diyProfessorScore.setFirstScore(60);//这下面两个日志都没有输出  就很奇怪   至少也因该输出一个  是不是有脏数据  我看看
        if (diyProfessorScoreService.getOne(new QueryWrapper<DiyProfessorScore>().eq("ding_user_id", diyProfessorScore.getDingUserId()))==null)
        {   log.info("专家分数为空，将初始化分数");
            diyProfessorScoreService.save(diyProfessorScore);}
        else
            {
                log.info("专家分数不为空，将更新分数");
                diyProfessorScoreService.update(diyProfessorScore,new UpdateWrapper<DiyProfessorScore>().eq("ding_user_id", diyProfessorScore.getDingUserId()));
            }
        log.info("返回前的信息=======================================>"+diyProfessorInfo);
        return diyProfessorInfo;
    }
    @Override
    public int updateDiyProfessorOneField(String dingUserId, String fieldName, int filedValue) {
        return diyProfessorInfoMapper.updateDiyProfessorOneField(dingUserId, fieldName, filedValue);
    }

    @Override
    public int updateDiyProfessorOneField(String dingUserId, String fieldName, String filedValue) {
        return diyProfessorInfoMapper.updateDiyProfessorOneField(dingUserId, fieldName, filedValue);
    }

    @Override
    public Integer deleteProfessorByDingId(String DingId) {
        log.debug(DingId);
        QueryWrapper<DiyProfessorInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("ding_user_id", DingId);

        return diyProfessorInfoMapper.delete(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteProfessorByUnionId(String unionId) {
        // 删除user_role表中的数据
        Integer result = sysBaseAPI.delRoleByUsername(unionId);
        log.debug("删除用户角色 ：" + result);
        // 删除user表中的数据
        return diyProfessorInfoMapper.deleteProfessorByUnionId(unionId);
    }

    @Override
    public DiyProfessorInfo queryProfessorInfoByUserId(String userid) {
        QueryWrapper<DiyProfessorInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("ding_user_id", userid);

        return diyProfessorInfoMapper.selectOne(wrapper);
    }

    @Override
    public void updateChangeInfo(String originator_userid) {
        UpdateWrapper<DiyProfessorInfo> wrapper = new UpdateWrapper<>();
        wrapper.set("is_change_info", 1)
                .eq("ding_user_id", originator_userid);
        diyProfessorInfoMapper.update(null, wrapper);
    }

    @Override
    public String exportPDF(List<String> list) {
        // 模板路径 D:\professorInfo.pdf
        String templatePath = uploadpath+File.separator+"professorInfo.pdf";
        log.info("获取pdf模板路径："+templatePath);
        File file = new File(templatePath);
        // 生成的新文件路径
        String filePath = UUID.randomUUID() +".pdf";
        String newPDFPath = uploadpath+File.separator+ filePath;
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            log.info("读取pdf模板");
            reader = new PdfReader(templatePath);// 读取pdf模板
            log.info("pdf模板读取完毕");
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            String[] arr = new String[list.size()];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = list.get(i);
                log.info("arr[i]=====>"+arr[i]);
            }
            log.info("开始pdf的设置");
            int i = 0;
            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            log.info("设置1");
            // 默认12号字体
            float fontSize = 12f;
            log.info("设置字号");
            // 设置中文字体
            BaseFont baseFont = BaseFont.createFont("HeiseiKakuGo-W5","UniJIS-UCS2-H", BaseFont.NOT_EMBEDDED);
            log.info("设置字体");
            while (it.hasNext()) {
                String name = it.next();
                log.info("进入循环name"+name);
                // 文本框宽度
                Rectangle position = form.getFieldPositions(name).get(0).position;
                float textBoxWidth = position.getWidth();
                // 文本框高度
                float textBoxHeight = position.getHeight();
                // 文本单行行高
                float ascent = baseFont.getFontDescriptor(BaseFont.ASCENT,fontSize);
                // baseFont渲染后的文字宽度
                float textWidth = baseFont.getWidthPoint( arr[i], fontSize);
              if (i<21&&i!=14&&i!=10){
                // 文本框高度只够写一行，并且文字宽度大于文本框宽度，则缩小字体
                if (textBoxHeight <= ascent * 1.6) {
                    while (textWidth >= textBoxWidth) {
                        fontSize--;
                        textWidth = baseFont.getWidthPoint( arr[i], fontSize);
                    }
                }else if(textWidth >= textBoxWidth){
                    while (textWidth >= textBoxWidth) {
                        fontSize--;
                        textWidth = baseFont.getWidthPoint( arr[i], fontSize);
                    }
                }
                }
              else if (i==14||i==10){
                  log.info("申报类别是=====>"+arr[i]);
                  System.out.println("arr[i] 申报类别是============= = " + arr[i]);
                  fontSize =8f;
              }
                form.setFieldProperty(name, "textsize", fontSize, null);
                System.out.println("name = 通过" + name);
                log.info("写入的区域"+name+"我要写入了====>"+arr[i]);
                form.setField(name, arr[i]);
                i++;
                fontSize=12f;
            }
            // 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.setFormFlattening(true);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();

        } catch (IOException e) {
            return null;
        } catch (DocumentException e) {
            return null;
        }
        // 成功返回1
        return filePath;
    }

    @Override
    public String getMajorNameById(String value) {
        return diyProfessorInfoMapper.selMajorNameById(value);
    }

    @Override
    public IPage<DiyProfessorInfo> pageByEntity(Page<DiyProfessorInfo> page, DiyProfessorInfo diyProfessorInfo) {
        List<DiyProfessorInfo> list = diyProfessorInfoMapper.pageByEntity(diyProfessorInfo);
        list.forEach((info)->{
            info.setProfessorMajor(diyProfessorInfoMapper.selMajorNameById(info.getProfessorMajor()));
            System.out.println(info);
        });

        page.setRecords(list);
        return page;
    }

}
